package com.g2room.test;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 数字映射 map
 * 
 * @author chenxu
 * 
 */
public class DigitalMap {
	@SuppressWarnings("unused")
	private static Log log = LogFactory.getLog(DigitalMap.class);

	/*
	 * 
	 * 每一位 对应方式不一样
	 */

	public final static short[] n0 = new short[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

	/*
	 * 
	 * ! warn 你不能修改这个数组
	 */
	private final static short[][] nmap = new short[][] { new short[] { 7, 3, 4, 1, 5, 2, 6, 0, 9, 8 }, new short[] { 1, 3, 7, 4, 6, 5, 2, 8, 9, 0 },
			new short[] { 7, 6, 1, 2, 9, 3, 5, 0, 4, 8 }, new short[] { 0, 5, 3, 6, 4, 1, 7, 9, 2, 8 }, new short[] { 6, 2, 9, 4, 1, 7, 0, 3, 5, 8 },
			new short[] { 0, 2, 4, 8, 6, 5, 7, 1, 9, 3 }, new short[] { 2, 0, 1, 7, 6, 4, 3, 5, 8, 9 }, new short[] { 5, 2, 0, 8, 7, 9, 3, 6, 4, 1 },
			new short[] { 3, 8, 9, 7, 4, 1, 5, 2, 6, 0 }, new short[] { 9, 4, 1, 7, 3, 2, 6, 8, 5, 0 } };

	/**
	 * 数字映射
	 * 
	 * @param l 原始数字
	 * @return 转换后的数字
	 */
	public static long map(long l) {
		String str = l + "";
		return NumberUtils.toLong(DigitalMap.map(str));
	}

	/**
	 * 数字映射
	 * 
	 * @param l 原始数字
	 * @return 转换后的数字
	 */
	public static String map(String str) {
		int len = str.length();

		StringBuilder result = new StringBuilder();
		for (int i = len - 1, j = 0; i >= 0; i--, j++) {
			result.append(convert(str.charAt(i), j));
		}
		result = result.reverse();

		return result.toString();

	}

	public static String exchangeNumber(String s, int len) {
		return exchangeNumber(NumberUtils.toLong(s),len);
	}
	
	public static String exchangeNumber(long l, int len) {
		final long seed = 8765412187L;
		l = (l + seed) % (new Double(Math.pow(10, len)).longValue());
		String no = TestMain.leftfillLength(l + "", len);

		int bit = NumberUtils.toInt(StringUtils.substring(no, no.length() - 1));
		int leftlen = 0;
		leftlen = bit % len;

		String left = StringUtils.substring(no, leftlen, len);
		String right = StringUtils.substring(no, 0, leftlen);

		no = left + right;
		return no;
	}

	/**
	 * 生成一位 数字
	 * 
	 * @param s
	 * @param i
	 * @return
	 */
	private static short convert(char s, int i) {
		int idx = i % nmap.length;
		short ss = Short.parseShort(s + "");
		short tars = nmap[idx][ss];
		return tars;
	}

	/**
	 * 随机 打乱 0-9
	 * 
	 * @return
	 */
	public static short[] getRandomOrder() {
		short[] x = ArrayUtils.clone(DigitalMap.n0);
		short[] rs = new short[] {};

		int len = x.length;
		for (int i = 0; i < len; i++) {
			int idx = RandomUtils.nextInt() % x.length;

			rs = ArrayUtils.add(rs, x[idx]);
			x = ArrayUtils.remove(x, idx);
		}
		return rs;
	}

}
